<template>
	<view class="audit-container">
		<!-- 搜索区域 -->
		<view class="search-section">
			<view class="search-box">
				<input 
					type="text"
					v-model="searchText"
					placeholder="请输入实体名称"
					class="search-input"
					@input="onSearch"
				/>
				<image 
					v-if="searchText"
					src="/static/images/clear.svg" 
					class="clear-icon" 
					mode="aspectFit"
					@tap="clearSearch"
				></image>
			</view>
		</view>

		<!-- 列表区域 -->
		<scroll-view 
			class="audit-scroll"
			scroll-y="true"
			@scrolltolower="loadMore"
			@refresherrefresh="onRefresh"
			:refresher-enabled="true"
			:refresher-triggered="isRefreshing"
		>
			<!-- 空状态 -->
			<view v-if="auditList.length === 0 && !isLoading" class="empty-state">
				<image 
					src="/static/images/no-data.svg" 
					mode="aspectFit" 
					class="empty-image"
				></image>
				<text class="empty-text">暂无审计日志</text>
			</view>

			<!-- 审计日志列表 -->
			<view v-else class="audit-list">
				<view 
					class="audit-card" 
					v-for="(audit, index) in auditList" 
					:key="index"
					@tap="goToDetail(audit)"
					:class="audit.actionStatus === 'SUCCESS' ? 'success-border' : 'error-border'"
				>
					<view class="card-content">
						<view class="first-line">
							<text class="audit-name">{{ audit.entityName || '-' }}</text>
							<text class="audit-time">{{ formatTime(audit.createdTime) }}</text>
						</view>
						<view class="second-line">
							<text class="audit-type">{{ formatEntityType(audit.entityId.entityType) }}</text>
							<text class="audit-status" :class="audit.actionStatus === 'SUCCESS' ? 'success' : 'error'">
								{{ formatStatus(audit.actionStatus) }}
							</text>
						</view>
						<view class="third-line">
							<text class="audit-action bold-text">{{ formatAction(audit.actionType) }}</text>
							<view class="info-icon-wrapper">
								<image 
									src="/static/images/arrow-right-2.svg" 
									mode="aspectFit" 
									class="info-icon"
								></image>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载状态 -->
				<view v-if="isLoading" class="loading-more">
					<text>加载中...</text>
				</view>

				<!-- 无更多数据 -->
				<view v-if="!hasMore && auditList.length > 0" class="no-more">
					<text>没有更多数据了</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import request from '@/utils/request.js'
import { formatTime } from '@/utils/timeUtils.js'

export default {
	data() {
		return {
			auditList: [],
			page: 0,
			pageSize: 10,
			hasMore: true,
			isLoading: false,
			isRefreshing: false,
			searchText: '',
			searchTimer: null,
			statusMap: {
				'SUCCESS': '成功',
				'FAILURE': '失败'
			},
			actionMap: {
				'ADDED': '已添加',
				'DELETED': '已删除',
				'UPDATED': '已更新',
				'ATTRIBUTES_UPDATED': '属性已更新',
				'ATTRIBUTES_DELETED': '属性已删除',
				'RPC_CALL': 'RPC调用',
				'CREDENTIALS_UPDATED': '凭证已更新',
				'ASSIGNED_TO_CUSTOMER': '已分配给客户',
				'UNASSIGNED_FROM_CUSTOMER': '已从客户取消分配',
				'ACTIVATED': '已激活',
				'SUSPENDED': '已暂停',
				'CREDENTIALS_READ': '已读取凭证',
				'ATTRIBUTES_READ': '已读取属性',
				'RELATION_ADD_OR_UPDATE': '关系已更新',
				'RELATION_DELETED': '关系已删除',
				'RELATIONS_DELETED': '所有关系已删除',
				'ALARM_ACK': '已确认',
				'ALARM_CLEAR': '已清除',
				'ALARM_DELETE': '告警已删除',
				'ALARM_ASSIGNED': '告警已分配',
				'ALARM_UNASSIGNED': '告警已取消分配',
				'LOGIN': '登录',
				'LOGOUT': '登出',
				'LOCKOUT': '已锁定',
				'ASSIGNED_FROM_TENANT': '已从租户分配',
				'ASSIGNED_TO_TENANT': '已分配给租户',
				'PROVISION_SUCCESS': '设备已配置',
				'PROVISION_FAILURE': '设备配置失败',
				'TIMESERIES_UPDATED': '遥测已更新',
				'TIMESERIES_DELETED': '遥测已删除',
				'ASSIGNED_TO_EDGE': '已分配给边缘',
				'UNASSIGNED_FROM_EDGE': '已从边缘取消分配',
				'ADDED_COMMENT': '已添加评论',
				'UPDATED_COMMENT': '已更新评论',
				'DELETED_COMMENT': '已删除评论',
				'SMS_SENT': '短信已发送'
			},
			entityTypeMap: {
				'TENANT': '租户',
				'TENANT_PROFILE': '租户配置',
				'CUSTOMER': '客户',
				'USER': '用户',
				'DASHBOARD': '仪表板',
				'ASSET': '资产',
				'DEVICE': '设备',
				'DEVICE_PROFILE': '设备配置',
				'ASSET_PROFILE': '资产配置',
				'ALARM': '告警',
				'RULE_CHAIN': '规则链',
				'RULE_NODE': '规则节点',
				'EDGE': '边缘',
				'ENTITY_VIEW': '实体视图',
				'WIDGETS_BUNDLE': '组件包',
				'WIDGET_TYPE': '组件类型',
				'API_USAGE_STATE': 'API使用状态',
				'TB_RESOURCE': '资源',
				'OTA_PACKAGE': 'OTA包',
				'RPC': 'RPC',
				'QUEUE': '队列',
				'NOTIFICATION_TARGET': '通知目标',
				'NOTIFICATION_TEMPLATE': '通知模板',
				'NOTIFICATION_REQUEST': '通知请求',
				'NOTIFICATION': '通知',
				'NOTIFICATION_RULE': '通知规则'
			}
		}
	},

	onLoad() {
		this.fetchAuditLogs()
	},

	methods: {
		formatTime,

		// 获取审计日志列表
		async fetchAuditLogs(isRefresh = false) {
			if (this.isLoading) return

			try {
				this.isLoading = true
				const params = {
					pageSize: this.pageSize,
					page: this.page,
					textSearch: this.searchText,
					sortProperty: 'createdTime',
					sortOrder: 'DESC'
				}

				const result = await request.get('/api/audit/logs', params)
				
				if (result && result.data) {
					if (isRefresh) {
						this.auditList = result.data
					} else {
						this.auditList = [...this.auditList, ...result.data]
					}
					this.hasMore = result.hasNext || false
				}
			} catch (error) {
				console.error('获取审计日志失败：', error)
				uni.showToast({
					title: '获取审计日志失败',
					icon: 'none'
				})
			} finally {
				this.isLoading = false
				if (isRefresh) {
					this.isRefreshing = false
					uni.stopPullDownRefresh()
				}
			}
		},

		// 搜索处理
		onSearch() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			this.searchTimer = setTimeout(() => {
				this.page = 0
				this.auditList = []
				this.hasMore = true
				this.fetchAuditLogs(true)
			}, 300)
		},

		// 清除搜索
		clearSearch() {
			this.searchText = ''
			this.onSearch()
		},

		// 下拉刷新
		async onRefresh() {
			if (this.isRefreshing || this.isLoading) return
			this.isRefreshing = true
			this.page = 0
			await this.fetchAuditLogs(true)
		},

		// 加载更多
		async loadMore() {
			if (!this.hasMore || this.isLoading || this.isRefreshing) return
			this.page++
			await this.fetchAuditLogs()
		},

		// 跳转到详情页
		goToDetail(audit) {
			uni.navigateTo({
				url: '/pages/more/auditLog/auditLogDetail?id=' + audit.id.id,
				success: function(res) {
					res.eventChannel.emit('auditData', { data: audit })
				}
			})
		},

		// 格式化状态显示
		formatStatus(status) {
			return this.statusMap[status] || '-'
		},

		// 格式化操作类型显示
		formatAction(action) {
			return this.actionMap[action] || '-'
		},

		// 格式化实体类型显示
		formatEntityType(type) {
			return this.entityTypeMap[type] || '-'
		}
	}
}
</script>

<style>
.audit-container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.search-section {
	background-color: #fff;
	padding: 10rpx 20rpx;
}

.search-box {
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 12rpx 20rpx;
	position: relative;
}

.search-input {
	flex: 1;
	font-size: 28rpx;
	padding-right: 60rpx;
}

.clear-icon {
	width: 40rpx;
	height: 40rpx;
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
}

.audit-scroll {
	height: calc(100vh - 90rpx);
}

.audit-list {
	padding: 16rpx 20rpx;
}

.audit-card {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-left: 8rpx solid transparent;
}

.success-border {
	border-left-color: #4CAF50;
}

.error-border {
	border-left-color: #F44336;
}

.card-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.first-line,
.second-line,
.third-line {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.audit-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.audit-time {
	font-size: 26rpx;
	color: #999;
}

.audit-type,
.audit-action {
	font-size: 26rpx;
	color: #999;
}

.audit-status {
	font-size: 26rpx;
	padding: 4rpx 12rpx;
	border-radius: 4rpx;
}

.audit-status.success {
	color: #4CAF50;
}

.audit-status.error {
	color: #F44336;
}

.info-icon-wrapper {
	width: 64rpx;
	height: 64rpx;
	background-color: #F3F6F9;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.info-icon {
	width: 32rpx;
	height: 32rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 240rpx;
	height: 240rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.loading-more, 
.no-more {
	text-align: center;
	padding: 30rpx 0;
	color: #999;
	font-size: 24rpx;
}

.bold-text {
	font-weight: 500;
}
</style>
